//
//  NetDownSupportFiles.m
//  KidReading
//
//  Created by telen on 15/3/17.
//  Copyright (c) 2015年 刘赞黄Telen. All rights reserved.
//

#import "NetDownSupportFiles.h"
#import "ConstDefine.h"

#if __Debug_CloseAES == 0
#define __FileCacheSupport @"TLSupportCache.telen"
#else
#define __FileCacheSupport @"TLSupportCache.txt"
#endif

@interface DownInfo_Net : NSObject
@property(nonatomic,assign)long long length;
@property(nonatomic,assign)long long done;
@property(nonatomic,assign)long long edition;
@property(nonatomic,strong)NSString* fileKey;
@end
@implementation DownInfo_Net
- (void)dealloc
{
    self.fileKey = nil;
}
@end



@implementation NetDownSupportFiles
{
    NSMutableDictionary* netCache;
    NSInteger downCount;
    NSInteger downIndex;
    //
    WaitingShow* waitshow;
    //
    id request_Ing;
}

static NetDownSupportFiles* netDownSupportFilesSingle = nil;

+ (NetDownSupportFiles *)getInstance
{
    if (!netDownSupportFilesSingle) {
        netDownSupportFilesSingle = [[NetDownSupportFiles alloc] init];
    }
    return netDownSupportFilesSingle;
}

- (instancetype)init
{
    if (self = [super init]) {
        NSString *documentsDirectory = [DataProcessing shareSingle].supportFilesDirector;
        NSString *SystemSave = [documentsDirectory stringByAppendingPathComponent:__FileCacheSupport];
#if __Debug_CloseAES == 0
        NSData* data = [[NSData alloc] initWithContentsOfFile:SystemSave];
        data = [data AES256DecryptWithKey:__AESKey];//解密
        @try {
            netCache = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        }
        @catch (NSException *exception) {
            NSLog(@"%@",exception);
        }
        @finally {
            
        }
        
#else
        netCache = [[NSMutableDictionary alloc] initWithContentsOfFile:SystemSave];
#endif
        if (!netCache) {
            netCache = [[NSMutableDictionary alloc] initWithCapacity:0];
        }
    }
    return self;
}

- (long long)getFlowBookHtmlZipEdition{
    return [netCache[@"flowbook"] longLongValue];
}

- (NSString*)getFlowBookHtmlEdition{
    return netCache[@"flowHtmlEdition"];
}


- (void)saveNetCache
{
    NSString *documentsDirectory = [DataProcessing shareSingle].supportFilesDirector;
    NSString *SystemSave         = [documentsDirectory stringByAppendingPathComponent:__FileCacheSupport];
    
#if __Debug_CloseAES == 0
    NSData* data = [NSKeyedArchiver archivedDataWithRootObject:netCache];
    data = [data AES256EncryptWithKey:__AESKey];//加密
    [data writeToFile:SystemSave atomically:YES];
#else
    [netCache writeToFile:SystemSave atomically:YES];
#endif
}

- (void)dealloc
{
    self.dict_Supports = nil;
}

- (void)checkDown
{
    if (_dict_Supports && request_Ing == nil) {
        NSArray* arr = [_dict_Supports allKeys];
        downCount = arr.count;
        downIndex = 0;
        BOOL isAllFinsh = YES;
        for (NSString* key in arr) {
            NSNumber* ed = [netCache objectForKey:key];
            NSDictionary* dict = [_dict_Supports objectForKey:key];
            nullToNil(dict);
            if (dict) {
                NSNumber* nub = [dict objectForKey:@"edition"];
                nullToNil(nub);
                if (nub) {
                    NSString* countryCode = dict[@"countryCode"];
                    nullToNil(countryCode);
                    if (_countryCode && _countryCode.length >0 && countryCode && countryCode.length >0 && ![_countryCode isEqualToString:countryCode]) {
                        downIndex++;
                        continue;
                    }
                    //
                    long long ed_net = [nub longLongValue];
                    if (!ed || [ed longLongValue] != ed_net) {
                        isAllFinsh = NO;
                        NSString* urlStr = [dict objectForKey:@"uri"];
                        nullToNil(urlStr)
                        if (urlStr) {
                            if ([key isEqualToString:@"flowbook"]) {
                                urlStr = [DataProcessing fullFlowBookHtmlUrl:urlStr];
                            }else if ([key isEqualToString:@"freval_data"]){
                                urlStr = [DataProcessing fullFrevalDataUrl:urlStr];
                            }else if ([key isEqualToString:@"quiz_common_script"]){
                                urlStr = [DataProcessing fullQuizCommonScriptUrl:urlStr];
                            }else{
                                urlStr = [DataProcessing fullSupportFileUrl:urlStr];
                            }

                            NSURL* url = [NSURL URLWithString:urlStr];
                            NSString* fileName = [urlStr lastPathComponent];
                            NSString* zipPath = [[DataProcessing shareSingle].supportFilesDirector stringByAppendingPathComponent:fileName];
                            NSString* tempPath = [zipPath stringByAppendingPathExtension:@"tl"];
                            DownInfo_Net* info = [[DownInfo_Net alloc] init];
                            info.edition = [nub longLongValue];
                            info.fileKey = key;
                            NSMutableDictionary* dict_th = [NSMutableDictionary dictionaryWithObjectsAndKeys:info,@"DownInfo_Net", nil];
                            //
                            JRASIHTTPRequest* asihttprequest = [JRASIHTTPRequest requestWithURL:url];
                            [asihttprequest setTemporaryFileDownloadPath:tempPath];
                            [asihttprequest setDownloadDestinationPath:zipPath];
                            [asihttprequest setUserInfo:dict_th];
                            [asihttprequest setDelegate:self];
                            [asihttprequest setDownloadProgressDelegate:self];
                            [asihttprequest setAllowResumeForFileDownloads:NO];//开关断点下载
                            [asihttprequest startAsynchronous];
                            request_Ing = asihttprequest;
                            break;
                        }
                    }
                }else{
                    NSLog(@"Net DictInfo Error");
                    if(waitshow){
                        [waitshow changeShowingSting:@"Down Fail" withAnimation:NO];
                        [waitshow hideShow];
                        waitshow = nil;
                        [[WaitingShow shareSingleShow] showString:NSLocalizedString(@"supportdownFail", "") andAutoHide:YES];
                    }
                }
            }
            downIndex++;
        }
    }
    //
    if(waitshow && downIndex == downCount){
        [waitshow hideShow];
        waitshow = nil;
        [WaitingShow shareSingleShow].centerOffset = CGPointMake(0, -30);
        if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
            [WaitingShow shareSingleShow].centerOffset = CGPointMake(0, -150);
        }
        [[WaitingShow shareSingleShow] showString:NSLocalizedString(@"supportdownOK", "") andAutoHide:YES];
    }
}

- (void)WaitingShow_AutoLayoutCaseView:(UIView *)caseView withWeihtHeight:(CGSize)size
{
    [caseView lyt_centerXInParentWithOffset:0];
    [caseView lyt_alignTopToParentWithMargin:3];
    [caseView lyt_setSize:size];
}

- (void)request:(JRASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
    NSMutableDictionary* userInfo = (NSMutableDictionary*)[request userInfo];
    DownInfo_Net* zipdowninfo = [userInfo objectForKey:@"DownInfo_Net"];
    if([responseHeaders objectForKey:@"Content-Length"]){
        zipdowninfo.length = [[responseHeaders objectForKey:@"Content-Length"] longLongValue];
    }
#if __Debug_Net
    NSLog(@"%@",responseHeaders);
#endif
}

- (void)requestFinished:(JRASIHTTPRequest *)request
{
#if __Debug_Net
    NSString* str2 = [request responseStatusMessage];
    NSString* str1 = [request responseString];
    NSLog(@"requestStatus:%@  requestMsg:%@",str2,str1);
    NSLog(@"URL: %@",[request url]);
#endif
    NSMutableDictionary* userInfo = (NSMutableDictionary*)[request userInfo];
    DownInfo_Net* zipdowninfo = [userInfo objectForKey:@"DownInfo_Net"];
    //
    NSString* file = [request downloadDestinationPath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
        BOOL result = NO;
        if (![file.lastPathComponent hasSuffix:@".zip"]) {
            result = YES;
        }
        if (!result) {
            if ([zipdowninfo.fileKey isEqualToString:@"flowbook"]) {
                NSString* copyZipPath = [[DataProcessing shareSingle].indexHtmlDirector stringByAppendingPathComponent:file.lastPathComponent];
                NSString* zipPath_old = [[DataProcessing shareSingle].indexHtmlDirector stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",[self getFlowBookHtmlEdition]]];
                if ([[NSFileManager defaultManager] fileExistsAtPath:zipPath_old]) {
                    [[NSFileManager defaultManager] removeItemAtPath:zipPath_old error:nil];
                }
                result = [[NSFileManager defaultManager] copyItemAtPath:file toPath:copyZipPath error:nil];
                NSString* htmlEdition = [[[request.url.absoluteString lastPathComponent] componentsSeparatedByString:@".zip"] firstObject];
                [netCache setObject:htmlEdition forKey:@"flowHtmlEdition"];
            }else if ([zipdowninfo.fileKey isEqualToString:@"freval_data"]){
                NSString* uzipPath = [file stringByDeletingLastPathComponent];
                JRZipArchive* zp = [[JRZipArchive alloc] init];
                [zp UnzipOpenFile:file];
                result = [zp UnzipFileTo:uzipPath overWrite:YES];
                [zp UnzipCloseFile];
            }else if ([zipdowninfo.fileKey isEqualToString:@"quiz_common_script"]){
                //NSLog(@"下载quiz结构数据完成");
                NSString* uzipPath = [DataProcessing shareSingle].quizDirector;
                JRZipArchive* zp = [[JRZipArchive alloc] init];
                [zp UnzipOpenFile:file];
                result = [zp UnzipFileTo:uzipPath overWrite:YES];
                [zp UnzipCloseFile];
            }else{
                NSString* uzipPath = [file stringByDeletingLastPathComponent];
                JRZipArchive* zp = [[JRZipArchive alloc] init];
                [zp UnzipOpenFile:file];
                result = [zp UnzipFileTo:uzipPath overWrite:YES];
                [zp UnzipCloseFile];
            }
        }
        if (!result) {
            NSLog(@"解压失败: %@",file);
        }
        else
        {
#if __Debug_DataProcessing
            NSLog(@"解压成功: %@",file);
#endif
            [netCache setObject:[NSNumber numberWithLongLong:zipdowninfo.edition] forKey:zipdowninfo.fileKey];
            [self saveNetCache];
            [[NSFileManager defaultManager] removeItemAtPath:file error:nil];
        }
    }
    //
    request_Ing = nil;
    [self checkDown];
}

- (void)requestFailed:(JRASIHTTPRequest *)request
{
#if __Debug_Net || __Debug_Net_Error
    NSString* str1 = [request responseString];
    NSString* str2 = [request responseStatusMessage];
    NSLog(@"requestStatus:%@  requestMsg:%@",str2,str1);
    NSURL* url = [request url];
    NSLog(@"requestFailed:errorURL: %@",url);
    NSLog(@"error: %@",request.error);
#endif
    //
    [waitshow hideShow],waitshow = nil;
    request_Ing = nil;
    [self performSelector:@selector(checkDown) withObject:nil afterDelay:1];
}

//断点续传时候，会有用
- (void)request:(JRASIHTTPRequest *)request incrementDownloadSizeBy:(long long)newLength
{
    NSMutableDictionary* userInfo = (NSMutableDictionary*)[request userInfo];
    DownInfo_Net* zipdowninfo = [userInfo objectForKey:@"DownInfo_Net"];
    zipdowninfo.length = newLength;
}

- (void)request:(JRASIHTTPRequest *)request didReceiveBytes:(long long)bytes
{
    if (!waitshow){
        waitshow = [WaitingShow createInstance];
        waitshow.delegate = self;
        [waitshow setDefaultWindow:_showSuperView];
        waitshow.textFont = [UIFont systemFontOfSize:9];
        [waitshow showString:[NSString stringWithFormat:@"  %@%.2f%@  ",NSLocalizedString(@"supportdown", ""),0.0,@"%"] andAutoHide:NO];
    }
    //
    NSMutableDictionary* userInfo = (NSMutableDictionary*)[request userInfo];
    DownInfo_Net* zipdowninfo = [userInfo objectForKey:@"DownInfo_Net"];
    zipdowninfo.done += bytes;
    //
    double pre = 100.0*zipdowninfo.done/zipdowninfo.length/downCount+100.0*downIndex/downCount;
    [waitshow changeShowingSting:[NSString stringWithFormat:@"%@%.2f%@",NSLocalizedString(@"supportdown", ""),pre,@"%"] withAnimation:NO];
#if __Debug_Net
    NSLog(@"DownInfo_Net:%@ size:%lld  done:%lld pre:%.2f%@",[[request downloadDestinationPath] lastPathComponent],zipdowninfo.length,zipdowninfo.done,pre,@"%");
#endif
}

@end
